<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>xv6 实验五 lazy page allocation | kiloGrand</title><meta name="keywords" content="xv6"><meta name="author" content="kiloGrand"><meta name="copyright" content="kiloGrand"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Lab traps: Trap https:&#x2F;&#x2F;pdos.csail.mit.edu&#x2F;6.S081&#x2F;2020&#x2F;schedule.html https:&#x2F;&#x2F;pdos.csail.mit.edu&#x2F;6.S081&#x2F;2020&#x2F;labs&#x2F;lazy.html  许多 OS 都会为用户的堆内存实现懒分配——在用户程序用 sbrk() 申请更多的空间时，不真正开辟物理内存，而是把要用的用户虚拟地址在页表中设为 in">
<meta property="og:type" content="article">
<meta property="og:title" content="xv6 实验五 lazy page allocation">
<meta property="og:url" content="https://kilogrand.gitee.io/2022/09/05/xv6-lab5/index.html">
<meta property="og:site_name" content="kiloGrand">
<meta property="og:description" content="Lab traps: Trap https:&#x2F;&#x2F;pdos.csail.mit.edu&#x2F;6.S081&#x2F;2020&#x2F;schedule.html https:&#x2F;&#x2F;pdos.csail.mit.edu&#x2F;6.S081&#x2F;2020&#x2F;labs&#x2F;lazy.html  许多 OS 都会为用户的堆内存实现懒分配——在用户程序用 sbrk() 申请更多的空间时，不真正开辟物理内存，而是把要用的用户虚拟地址在页表中设为 in">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://kilogrand.gitee.io/img/coding.jpg">
<meta property="article:published_time" content="2022-09-05T01:41:10.000Z">
<meta property="article:modified_time" content="2023-02-19T13:47:46.020Z">
<meta property="article:author" content="kiloGrand">
<meta property="article:tag" content="xv6">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://kilogrand.gitee.io/img/coding.jpg"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://kilogrand.gitee.io/2022/09/05/xv6-lab5/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'xv6 实验五 lazy page allocation',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-02-19 21:47:46'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.2"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/profile.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">46</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">6</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/img/coding.jpg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">kiloGrand</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> Link</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">xv6 实验五 lazy page allocation</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-09-05T01:41:10.000Z" title="发表于 2022-09-05 09:41:10">2022-09-05</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-02-19T13:47:46.020Z" title="更新于 2023-02-19 21:47:46">2023-02-19</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">操作系统</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.5k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>12分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="xv6 实验五 lazy page allocation"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="Lab-traps-Trap"><a href="#Lab-traps-Trap" class="headerlink" title="Lab traps: Trap"></a>Lab traps: Trap</h1><ul>
<li><a target="_blank" rel="noopener" href="https://pdos.csail.mit.edu/6.S081/2020/schedule.html">https://pdos.csail.mit.edu/6.S081/2020/schedule.html</a></li>
<li><a target="_blank" rel="noopener" href="https://pdos.csail.mit.edu/6.S081/2020/labs/lazy.html">https://pdos.csail.mit.edu/6.S081/2020/labs/lazy.html</a></li>
</ul>
<p>许多 OS 都会为用户的堆内存实现懒分配——在用户程序用 sbrk() 申请更多的空间时，不真正开辟物理内存，而是把要用的用户虚拟地址在页表中设为 invalid，等到确实用到了这个虚拟地址，CPU 产生缺页错误，这时内核再分配物理内存。</p>
<h2 id="Eliminate-allocation-from-sbrk-easy"><a href="#Eliminate-allocation-from-sbrk-easy" class="headerlink" title="Eliminate allocation from sbrk() (easy)"></a>Eliminate allocation from sbrk() (easy)</h2><p>任务：在 sys_sbrk (kernel/sysproc.c) 中修改 xv6 原本的 sbrk(n) 系统调用的实现。原本的 sbrk(n) 会让用户空间增长 n 个字节，返回新分配虚拟空间的首地址（即原用户空间大小）。新的 sbrk(n) 应该只给 myproc()-&gt;sz 加上 n，返回原用户空间大小，但是并没有实际开辟物理内存，不再调用 growproc()。<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/sysproc.c</span></span><br><span class="line">uint64</span><br><span class="line"><span class="title function_">sys_sbrk</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">  ...</span><br><span class="line">  addr = myproc()-&gt;sz;</span><br><span class="line">  myproc()-&gt;sz += n;  <span class="comment">// 懒分配</span></span><br><span class="line"><span class="comment">//  if(growproc(n) &lt; 0)</span></span><br><span class="line"><span class="comment">//    return -1;</span></span><br><span class="line">  <span class="keyword">return</span> addr;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><br>现在编译 xv6，输入 <code>echo hi</code>，则会出错：<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">$ <span class="built_in">echo</span> hi</span><br><span class="line">usertrap(): unexpected scause 0x000000000000000f pid=3</span><br><span class="line">            sepc=0x00000000000012ac stval=0x0000000000004008</span><br><span class="line">panic: uvmunmap: not mapped</span><br></pre></td></tr></table></figure></p>
<h2 id="Lazy-allocation-moderate"><a href="#Lazy-allocation-moderate" class="headerlink" title="Lazy allocation (moderate)"></a>Lazy allocation (moderate)</h2><p>任务：改变 trap.c 的代码以回应用户空间的缺页错误，即新开辟一页的物理内存空间，返回用户空间继续执行。</p>
<p>我们首先在 usertrap 中处理缺页错误。缺页错误的代码是 13 或 15，当发生缺页错误时，判断是否是懒分配引起的（引起错误的地址在 p-&gt;sz 内），如果是，则用 kalloc 新开辟一页物理空间，并在页表中加上缺页的地址所在页面这一项。<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/trap.c</span></span><br><span class="line"><span class="type">void</span></span><br><span class="line"><span class="title function_">usertrap</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">  ...</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    uint64 cause = r_scause();</span><br><span class="line">    <span class="keyword">if</span>(cause == <span class="number">13</span> || cause == <span class="number">15</span>)&#123;</span><br><span class="line">      <span class="comment">// page fault</span></span><br><span class="line">      uint64 stval = r_stval();</span><br><span class="line">      <span class="keyword">if</span>(stval &lt; p-&gt;sz)&#123;</span><br><span class="line">        <span class="comment">// need lazy allocation</span></span><br><span class="line">        <span class="type">char</span> *mem = kalloc();</span><br><span class="line">        <span class="keyword">if</span>(mem)&#123;</span><br><span class="line">          <span class="built_in">memset</span>(mem, <span class="number">0</span>, PGSIZE);</span><br><span class="line">          <span class="keyword">if</span>(mappages(p-&gt;pagetable, PGROUNDDOWN(stval), PGSIZE, (uint64)mem, PTE_W|PTE_X|PTE_R|PTE_U) != <span class="number">0</span>)&#123;</span><br><span class="line">            kfree(mem);</span><br><span class="line">            uvmunmap(p-&gt;pagetable, PGROUNDDOWN(stval), <span class="number">1</span>, <span class="number">1</span>);</span><br><span class="line">          &#125; <span class="keyword">else</span> <span class="keyword">goto</span> brk;</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;usertrap(): unexpected scause %p pid=%d\n&quot;</span>, r_scause(), p-&gt;pid);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;            sepc=%p stval=%p\n&quot;</span>, r_sepc(), r_stval());</span><br><span class="line">    p-&gt;killed = <span class="number">1</span>;</span><br><span class="line">  &#125;</span><br><span class="line">brk:</span><br></pre></td></tr></table></figure></p>
<p>我们还需要更改 uvmunmap 的内容，这是因为加入懒分配之后，uvmunmap 可能会被要求解除本就不存在的映射、或者去找还没有创建的 pte。在原本的写法中这样会 panic，因此，我们要把 panic 改掉：<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/vm.c</span></span><br><span class="line"><span class="type">void</span></span><br><span class="line"><span class="title function_">uvmunmap</span><span class="params">(<span class="type">pagetable_t</span> pagetable, uint64 va, uint64 npages, <span class="type">int</span> do_free)</span></span><br><span class="line">&#123;</span><br><span class="line">  ...</span><br><span class="line">    <span class="keyword">if</span>((pte = walk(pagetable, a, <span class="number">0</span>)) == <span class="number">0</span>)</span><br><span class="line">      <span class="keyword">continue</span>; <span class="comment">// panic(&quot;uvmunmap: walk&quot;);</span></span><br><span class="line">    <span class="keyword">if</span>((*pte &amp; PTE_V) == <span class="number">0</span>)</span><br><span class="line">      <span class="keyword">continue</span>; <span class="comment">// panic(&quot;uvmunmap: not mapped&quot;);</span></span><br><span class="line">  ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><br>现在我们已经能正常执行 <code>echo hi</code> 了。</p>
<h2 id="Lazytests-and-Usertests-moderate"><a href="#Lazytests-and-Usertests-moderate" class="headerlink" title="Lazytests and Usertests (moderate)"></a>Lazytests and Usertests (moderate)</h2><p>任务：通过 Lazytests 和 Usertests。</p>
<p>完成上一小节的任务后，我们的代码其实并不完善，还需要处理下列问题：</p>
<ol>
<li>处理负的 sbrk() 参数</li>
<li>如果导致缺页错误的虚拟地址高于任何 sbrk() 分配的内存地址，则杀死进程</li>
<li>在 fork() 中正确处理父进程到子进程的内存复制</li>
<li>处理以下情况：一个进程给系统调用（如 read / write）传入了一个合法的地址，但是地址的内存还没有分配</li>
<li>正确处理超出内存的情况：如果 kalloc() 在缺页错误处理中失败了，则杀死进程</li>
<li>处理缺页错误中访问用户栈之下的非法空间</li>
</ol>
<p>对于第 1 点，只需要参照 growproc 原本的写法，如果 n &lt; 0，则调用 uvmdealloc 回收空间：<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/sysproc.c</span></span><br><span class="line">uint64</span><br><span class="line"><span class="title function_">sys_sbrk</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">  ...</span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">proc</span> *<span class="title">p</span> =</span> myproc();</span><br><span class="line">  addr = p-&gt;sz;</span><br><span class="line">  <span class="keyword">if</span>(n &gt; <span class="number">0</span>)</span><br><span class="line">    p-&gt;sz += n;</span><br><span class="line">  <span class="keyword">else</span></span><br><span class="line">    p-&gt;sz = uvmdealloc(p-&gt;pagetable, addr, addr+n);</span><br><span class="line">  <span class="keyword">return</span> addr;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>对于第 2、5、6 点，只需要在上一小节的基础上加一点判断和 killed 设置即可，为了方便，这次把处理代码写成一个函数（kernel/proc.c 中）：<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/proc.c</span></span><br><span class="line"><span class="comment">// Handle page fault with lazy allocation</span></span><br><span class="line"><span class="type">int</span></span><br><span class="line"><span class="title function_">lazy_allocate</span><span class="params">(uint64 va)</span>&#123;</span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">proc</span> *<span class="title">p</span> =</span> myproc();</span><br><span class="line">  <span class="keyword">if</span>(va &gt;= p-&gt;sz || va &lt; p-&gt;trapframe-&gt;sp)</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">  <span class="type">char</span> *mem = kalloc();</span><br><span class="line">  <span class="keyword">if</span>(mem == <span class="number">0</span>)</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">  <span class="built_in">memset</span>(mem, <span class="number">0</span>, PGSIZE);</span><br><span class="line">  <span class="keyword">if</span>(mappages(p-&gt;pagetable, PGROUNDDOWN(va), PGSIZE, (uint64)mem, PTE_W|PTE_X|PTE_R|PTE_U) != <span class="number">0</span>)&#123;</span><br><span class="line">    kfree(mem);</span><br><span class="line">    uvmunmap(p-&gt;pagetable, PGROUNDDOWN(va), <span class="number">1</span>, <span class="number">1</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><br>在kernel/defs.h添加声明</p>
<p>于是乎，在 usertrap 中我们只需要调用 lazy_allocate：<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/trap.c</span></span><br><span class="line"><span class="type">void</span></span><br><span class="line"><span class="title function_">usertrap</span><span class="params">(<span class="type">void</span>)</span></span><br><span class="line">&#123;</span><br><span class="line">  ...</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    uint64 cause = r_scause();</span><br><span class="line">    <span class="keyword">if</span>(cause == <span class="number">13</span> || cause == <span class="number">15</span>)&#123;</span><br><span class="line">      <span class="comment">// page fault</span></span><br><span class="line">      uint64 stval = r_stval();</span><br><span class="line">      <span class="keyword">if</span>(lazy_allocate(stval) == <span class="number">0</span>)</span><br><span class="line">        <span class="keyword">goto</span> brk;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;usertrap(): unexpected scause %p pid=%d\n&quot;</span>, r_scause(), p-&gt;pid);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;            sepc=%p stval=%p\n&quot;</span>, r_sepc(), r_stval());</span><br><span class="line">    p-&gt;killed = <span class="number">1</span>;</span><br><span class="line">  &#125;</span><br><span class="line">brk:</span><br></pre></td></tr></table></figure></p>
<p>对于第 3 点，我们查看 fork 的代码，发现内存复制是调用 uvmcopy 实现的，所以只需要像改 uvmunmap 一般改 uvmcopy 即可：<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/vm.c</span></span><br><span class="line"><span class="type">int</span></span><br><span class="line"><span class="title function_">uvmcopy</span><span class="params">(<span class="type">pagetable_t</span> old, <span class="type">pagetable_t</span> new, uint64 sz)</span></span><br><span class="line">&#123;</span><br><span class="line">  ...</span><br><span class="line">  <span class="keyword">for</span>(i = <span class="number">0</span>; i &lt; sz; i += PGSIZE)&#123;</span><br><span class="line">    <span class="keyword">if</span>((pte = walk(old, i, <span class="number">0</span>)) == <span class="number">0</span>)</span><br><span class="line">      <span class="keyword">continue</span>; <span class="comment">// panic(&quot;uvmcopy: pte should exist&quot;);</span></span><br><span class="line">    <span class="keyword">if</span>((*pte &amp; PTE_V) == <span class="number">0</span>)</span><br><span class="line">      <span class="keyword">continue</span>; <span class="comment">// panic(&quot;uvmcopy: page not present&quot;);</span></span><br><span class="line">  ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>对于第 4 点，系统调用的时候 RISC-V 硬件不会引发缺页错误，因此操作系统必须处理这种情况。我们知道，那些参数包含地址的系统调用都会执行 argaddr() 函数，所以我们先找到它（kernel/syscall.c）。理论上，在这里处理缺页是可行的，但是我们把目光向上移，就会发现注释说：argaddr() 不检查是否合法，因为 copyin/copyout 会检查。好吧，那我们就去看看 copyin/copyout 是怎么检查的呗。看了一圈下来，我们可以发现，它们会调用 walkaddr()，如果 walkaddr 返回 0，那么就返回错误代码 -1。所以，<strong>本质上是 walkaddr() 在检查是否合法！</strong>Okay，定位了问题所在，我们只需要用上刚刚写的 lazy_allocate() 函数，略微修改 walkaddr() 即可：<br><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// kernel/vm.c</span></span><br><span class="line">uint64</span><br><span class="line"><span class="title function_">walkaddr</span><span class="params">(<span class="type">pagetable_t</span> pagetable, uint64 va)</span></span><br><span class="line">&#123;</span><br><span class="line">  ...</span><br><span class="line">  pte = walk(pagetable, va, <span class="number">0</span>);</span><br><span class="line">  <span class="keyword">if</span>(pte == <span class="number">0</span> || (*pte &amp; PTE_V) == <span class="number">0</span>)&#123;</span><br><span class="line">    <span class="keyword">if</span>(lazy_allocate(va) != <span class="number">0</span>)</span><br><span class="line">      <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    pte = walk(pagetable, va, <span class="number">0</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>make grade结果:<br><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br></pre></td><td class="code"><pre><span class="line">grand@Lubuntu ~/xv6-labs-2020 (lazy)&gt; ./grade-lab-lazy</span><br><span class="line">make: <span class="string">&#x27;kernel/kernel&#x27;</span> is up to <span class="built_in">date</span>.</span><br><span class="line">== Test running lazytests == (11.1s) </span><br><span class="line">== Test   lazy: map == </span><br><span class="line">  lazy: map: OK </span><br><span class="line">== Test   lazy: unmap == </span><br><span class="line">  lazy: unmap: OK </span><br><span class="line">== Test usertests == (433.9s) </span><br><span class="line">== Test   usertests: pgbug == </span><br><span class="line">  usertests: pgbug: OK </span><br><span class="line">== Test   usertests: sbrkbugs == </span><br><span class="line">  usertests: sbrkbugs: OK </span><br><span class="line">== Test   usertests: argptest == </span><br><span class="line">  usertests: argptest: OK </span><br><span class="line">== Test   usertests: sbrkmuch == </span><br><span class="line">  usertests: sbrkmuch: OK </span><br><span class="line">== Test   usertests: sbrkfail == </span><br><span class="line">  usertests: sbrkfail: OK </span><br><span class="line">== Test   usertests: sbrkarg == </span><br><span class="line">  usertests: sbrkarg: OK </span><br><span class="line">== Test   usertests: stacktest == </span><br><span class="line">  usertests: stacktest: OK </span><br><span class="line">== Test   usertests: execout == </span><br><span class="line">  usertests: execout: OK </span><br><span class="line">== Test   usertests: copyin == </span><br><span class="line">  usertests: copyin: OK </span><br><span class="line">== Test   usertests: copyout == </span><br><span class="line">  usertests: copyout: OK </span><br><span class="line">== Test   usertests: copyinstr1 == </span><br><span class="line">  usertests: copyinstr1: OK </span><br><span class="line">== Test   usertests: copyinstr2 == </span><br><span class="line">  usertests: copyinstr2: OK </span><br><span class="line">== Test   usertests: copyinstr3 == </span><br><span class="line">  usertests: copyinstr3: OK </span><br><span class="line">== Test   usertests: rwsbrk == </span><br><span class="line">  usertests: rwsbrk: OK </span><br><span class="line">== Test   usertests: truncate1 == </span><br><span class="line">  usertests: truncate1: OK </span><br><span class="line">== Test   usertests: truncate2 == </span><br><span class="line">  usertests: truncate2: OK </span><br><span class="line">== Test   usertests: truncate3 == </span><br><span class="line">  usertests: truncate3: OK </span><br><span class="line">== Test   usertests: reparent2 == </span><br><span class="line">  usertests: reparent2: OK </span><br><span class="line">== Test   usertests: badarg == </span><br><span class="line">  usertests: badarg: OK </span><br><span class="line">== Test   usertests: reparent == </span><br><span class="line">  usertests: reparent: OK </span><br><span class="line">== Test   usertests: twochildren == </span><br><span class="line">  usertests: twochildren: OK </span><br><span class="line">== Test   usertests: forkfork == </span><br><span class="line">  usertests: forkfork: OK </span><br><span class="line">== Test   usertests: forkforkfork == </span><br><span class="line">  usertests: forkforkfork: OK </span><br><span class="line">== Test   usertests: createdelete == </span><br><span class="line">  usertests: createdelete: OK </span><br><span class="line">== Test   usertests: linkunlink == </span><br><span class="line">  usertests: linkunlink: OK </span><br><span class="line">== Test   usertests: linktest == </span><br><span class="line">  usertests: linktest: OK </span><br><span class="line">== Test   usertests: unlinkread == </span><br><span class="line">  usertests: unlinkread: OK </span><br><span class="line">== Test   usertests: concreate == </span><br><span class="line">  usertests: concreate: OK </span><br><span class="line">== Test   usertests: subdir == </span><br><span class="line">  usertests: subdir: OK </span><br><span class="line">== Test   usertests: fourfiles == </span><br><span class="line">  usertests: fourfiles: OK </span><br><span class="line">== Test   usertests: sharedfd == </span><br><span class="line">  usertests: sharedfd: OK </span><br><span class="line">== Test   usertests: exectest == </span><br><span class="line">  usertests: exectest: OK </span><br><span class="line">== Test   usertests: bigargtest == </span><br><span class="line">  usertests: bigargtest: OK </span><br><span class="line">== Test   usertests: bigwrite == </span><br><span class="line">  usertests: bigwrite: OK </span><br><span class="line">== Test   usertests: bsstest == </span><br><span class="line">  usertests: bsstest: OK </span><br><span class="line">== Test   usertests: sbrkbasic == </span><br><span class="line">  usertests: sbrkbasic: OK </span><br><span class="line">== Test   usertests: kernmem == </span><br><span class="line">  usertests: kernmem: OK </span><br><span class="line">== Test   usertests: validatetest == </span><br><span class="line">  usertests: validatetest: OK </span><br><span class="line">== Test   usertests: opentest == </span><br><span class="line">  usertests: opentest: OK </span><br><span class="line">== Test   usertests: writetest == </span><br><span class="line">  usertests: writetest: OK </span><br><span class="line">== Test   usertests: writebig == </span><br><span class="line">  usertests: writebig: OK </span><br><span class="line">== Test   usertests: createtest == </span><br><span class="line">  usertests: createtest: OK </span><br><span class="line">== Test   usertests: openiput == </span><br><span class="line">  usertests: openiput: OK </span><br><span class="line">== Test   usertests: exitiput == </span><br><span class="line">  usertests: exitiput: OK </span><br><span class="line">== Test   usertests: iput == </span><br><span class="line">  usertests: iput: OK </span><br><span class="line">== Test   usertests: mem == </span><br><span class="line">  usertests: mem: OK </span><br><span class="line">== Test   usertests: pipe1 == </span><br><span class="line">  usertests: pipe1: OK </span><br><span class="line">== Test   usertests: preempt == </span><br><span class="line">  usertests: preempt: OK </span><br><span class="line">== Test   usertests: exitwait == </span><br><span class="line">  usertests: exitwait: OK </span><br><span class="line">== Test   usertests: rmdot == </span><br><span class="line">  usertests: rmdot: OK </span><br><span class="line">== Test   usertests: fourteen == </span><br><span class="line">  usertests: fourteen: OK </span><br><span class="line">== Test   usertests: bigfile == </span><br><span class="line">  usertests: bigfile: OK </span><br><span class="line">== Test   usertests: dirfile == </span><br><span class="line">  usertests: dirfile: OK </span><br><span class="line">== Test   usertests: iref == </span><br><span class="line">  usertests: iref: OK </span><br><span class="line">== Test   usertests: forktest == </span><br><span class="line">  usertests: forktest: OK </span><br><span class="line">== Test time == </span><br><span class="line">time: FAIL </span><br><span class="line">    time.txt does not contain a single <span class="built_in">integer</span> (number of hours spent on the lab)</span><br><span class="line">Score: 118/119</span><br></pre></td></tr></table></figure></p>
<h2 id="修改记录"><a href="#修改记录" class="headerlink" title="修改记录"></a>修改记录</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br></pre></td><td class="code"><pre><span class="line">diff --git a/grade-lab-lazy b/grade-lab-lazy</span><br><span class="line">index 06bde03..7455602 100755</span><br><span class="line">--- a/grade-lab-lazy</span><br><span class="line">+++ b/grade-lab-lazy</span><br><span class="line">@@ -23,7 +23,7 @@ def test_memtest():</span><br><span class="line"> def test_usertests():</span><br><span class="line">     r.run_qemu(shell_script([</span><br><span class="line">         &#x27;usertests&#x27;</span><br><span class="line">-    ]), timeout=300)</span><br><span class="line">+    ]), timeout=600)</span><br><span class="line"> </span><br><span class="line"> def usertest_check(testcase, nextcase, output):</span><br><span class="line">     if not re.search(r&#x27;\ntest &#123;&#125;: [\s\S]*OK\ntest &#123;&#125;&#x27;.format(testcase, nextcase), output):</span><br><span class="line">diff --git a/kernel/defs.h b/kernel/defs.h</span><br><span class="line">index 4b9bbc0..04140f6 100644</span><br><span class="line">--- a/kernel/defs.h</span><br><span class="line">+++ b/kernel/defs.h</span><br><span class="line">@@ -104,6 +104,7 @@ void            yield(void);</span><br><span class="line"> int             either_copyout(int user_dst, uint64 dst, void *src, uint64 len);</span><br><span class="line"> int             either_copyin(void *dst, int user_src, uint64 src, uint64 len);</span><br><span class="line"> void            procdump(void);</span><br><span class="line">+int             lazy_allocate(uint64);</span><br><span class="line"> </span><br><span class="line"> // swtch.S</span><br><span class="line"> void            swtch(struct context*, struct context*);</span><br><span class="line">diff --git a/kernel/proc.c b/kernel/proc.c</span><br><span class="line">index ebbf5a2..de492bd 100644</span><br><span class="line">--- a/kernel/proc.c</span><br><span class="line">+++ b/kernel/proc.c</span><br><span class="line">@@ -694,3 +694,21 @@ procdump(void)</span><br><span class="line">     printf(&quot;\n&quot;);</span><br><span class="line">   &#125;</span><br><span class="line"> &#125;</span><br><span class="line">+</span><br><span class="line">+// Handle page fault with lazy allocation</span><br><span class="line">+int</span><br><span class="line">+lazy_allocate(uint64 va)&#123;</span><br><span class="line">+  struct proc *p = myproc();</span><br><span class="line">+  if(va &gt;= p-&gt;sz || va &lt; p-&gt;trapframe-&gt;sp)</span><br><span class="line">+    return -1;</span><br><span class="line">+  char *mem = kalloc();</span><br><span class="line">+  if(mem == 0)</span><br><span class="line">+    return -1;</span><br><span class="line">+  memset(mem, 0, PGSIZE);</span><br><span class="line">+  if(mappages(p-&gt;pagetable, PGROUNDDOWN(va), PGSIZE, (uint64)mem, PTE_W|PTE_X|PTE_R|PTE_U) != 0)&#123;</span><br><span class="line">+    kfree(mem);</span><br><span class="line">+    uvmunmap(p-&gt;pagetable, PGROUNDDOWN(va), 1, 1);</span><br><span class="line">+    return -1;</span><br><span class="line">+  &#125;</span><br><span class="line">+  return 0;</span><br><span class="line">+&#125;</span><br><span class="line">diff --git a/kernel/sysproc.c b/kernel/sysproc.c</span><br><span class="line">index e8bcda9..31fa244 100644</span><br><span class="line">--- a/kernel/sysproc.c</span><br><span class="line">+++ b/kernel/sysproc.c</span><br><span class="line">@@ -46,9 +46,12 @@ sys_sbrk(void)</span><br><span class="line"> </span><br><span class="line">   if(argint(0, &amp;n) &lt; 0)</span><br><span class="line">     return -1;</span><br><span class="line">-  addr = myproc()-&gt;sz;</span><br><span class="line">-  if(growproc(n) &lt; 0)</span><br><span class="line">-    return -1;</span><br><span class="line">+  struct proc *p = myproc();</span><br><span class="line">+  addr = p-&gt;sz;</span><br><span class="line">+  if(n &gt; 0)</span><br><span class="line">+    p-&gt;sz += n; // lazy allocation</span><br><span class="line">+  else</span><br><span class="line">+	p-&gt;sz = uvmdealloc(p-&gt;pagetable, addr, addr+n);</span><br><span class="line">   return addr;</span><br><span class="line"> &#125;</span><br><span class="line"> </span><br><span class="line">diff --git a/kernel/trap.c b/kernel/trap.c</span><br><span class="line">index a63249e..e726913 100644</span><br><span class="line">--- a/kernel/trap.c</span><br><span class="line">+++ b/kernel/trap.c</span><br><span class="line">@@ -68,11 +68,18 @@ usertrap(void)</span><br><span class="line">   &#125; else if((which_dev = devintr()) != 0)&#123;</span><br><span class="line">     // ok</span><br><span class="line">   &#125; else &#123;</span><br><span class="line">+	uint64 cause = r_scause();</span><br><span class="line">+	if(cause == 13 || cause == 15) &#123;</span><br><span class="line">+	  // page fault</span><br><span class="line">+	  uint64 stval = r_stval();</span><br><span class="line">+	  if(lazy_allocate(stval) == 0)</span><br><span class="line">+	    goto brk;</span><br><span class="line">+	&#125;</span><br><span class="line">     printf(&quot;usertrap(): unexpected scause %p pid=%d\n&quot;, r_scause(), p-&gt;pid);</span><br><span class="line">     printf(&quot;            sepc=%p stval=%p\n&quot;, r_sepc(), r_stval());</span><br><span class="line">     p-&gt;killed = 1;</span><br><span class="line">   &#125;</span><br><span class="line">-</span><br><span class="line">+brk:</span><br><span class="line">   if(p-&gt;killed)</span><br><span class="line">     exit(-1);</span><br><span class="line"> </span><br><span class="line">diff --git a/kernel/vm.c b/kernel/vm.c</span><br><span class="line">index bccb405..c159529 100644</span><br><span class="line">--- a/kernel/vm.c</span><br><span class="line">+++ b/kernel/vm.c</span><br><span class="line">@@ -101,10 +101,11 @@ walkaddr(pagetable_t pagetable, uint64 va)</span><br><span class="line">     return 0;</span><br><span class="line"> </span><br><span class="line">   pte = walk(pagetable, va, 0);</span><br><span class="line">-  if(pte == 0)</span><br><span class="line">-    return 0;</span><br><span class="line">-  if((*pte &amp; PTE_V) == 0)</span><br><span class="line">-    return 0;</span><br><span class="line">+  if(pte == 0 || (*pte &amp; PTE_V) == 0) &#123;</span><br><span class="line">+    if(lazy_allocate(va) != 0)</span><br><span class="line">+      return 0;</span><br><span class="line">+	pte = walk(pagetable, va, 0);</span><br><span class="line">+  &#125;</span><br><span class="line">   if((*pte &amp; PTE_U) == 0)</span><br><span class="line">     return 0;</span><br><span class="line">   pa = PTE2PA(*pte);</span><br><span class="line">@@ -181,9 +182,9 @@ uvmunmap(pagetable_t pagetable, uint64 va, uint64 npages, int do_free)</span><br><span class="line"> </span><br><span class="line">   for(a = va; a &lt; va + npages*PGSIZE; a += PGSIZE)&#123;</span><br><span class="line">     if((pte = walk(pagetable, a, 0)) == 0)</span><br><span class="line">-      panic(&quot;uvmunmap: walk&quot;);</span><br><span class="line">+      continue; // panic(&quot;uvmunmap: walk&quot;);</span><br><span class="line">     if((*pte &amp; PTE_V) == 0)</span><br><span class="line">-      panic(&quot;uvmunmap: not mapped&quot;);</span><br><span class="line">+      continue; // panic(&quot;uvmunmap: not mapped&quot;);</span><br><span class="line">     if(PTE_FLAGS(*pte) == PTE_V)</span><br><span class="line">       panic(&quot;uvmunmap: not a leaf&quot;);</span><br><span class="line">     if(do_free)&#123;</span><br><span class="line">@@ -315,9 +316,9 @@ uvmcopy(pagetable_t old, pagetable_t new, uint64 sz)</span><br><span class="line"> </span><br><span class="line">   for(i = 0; i &lt; sz; i += PGSIZE)&#123;</span><br><span class="line">     if((pte = walk(old, i, 0)) == 0)</span><br><span class="line">-      panic(&quot;uvmcopy: pte should exist&quot;);</span><br><span class="line">+      continue; // panic(&quot;uvmcopy: pte should exist&quot;);</span><br><span class="line">     if((*pte &amp; PTE_V) == 0)</span><br><span class="line">-      panic(&quot;uvmcopy: page not present&quot;);</span><br><span class="line">+      continue; // panic(&quot;uvmcopy: page not present&quot;);</span><br><span class="line">     pa = PTE2PA(*pte);</span><br><span class="line">     flags = PTE_FLAGS(*pte);</span><br><span class="line">     if((mem = kalloc()) == 0)</span><br><span class="line">diff --git a/time.txt b/time.txt</span><br><span class="line">new file mode 100644</span><br><span class="line">index 0000000..4ae1932</span><br><span class="line">--- /dev/null</span><br><span class="line">+++ b/time.txt</span><br><span class="line">@@ -0,0 +1 @@</span><br><span class="line">+10h10h10h10h10h10h10h10h10h10h</span><br></pre></td></tr></table></figure></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://kilogrand.gitee.io">kiloGrand</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://kilogrand.gitee.io/2022/09/05/xv6-lab5/">https://kilogrand.gitee.io/2022/09/05/xv6-lab5/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://kilogrand.gitee.io" target="_blank">kiloGrand</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/xv6/">xv6</a></div><div class="post_share"></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2022/09/05/xv6-lab6/"><img class="prev-cover" src="/img/coding.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">xv6 实验六 Copy-on-Write Fork</div></div></a></div><div class="next-post pull-right"><a href="/2022/09/06/xv6-lab7/"><img class="next-cover" src="/img/coding.jpg" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">xv6 实验七 Multithreading</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2022/08/31/xv6-Chapter-0/" title="xv6 riscv book 中文版声明"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 riscv book 中文版声明</div></div></a></div><div><a href="/2022/08/31/xv6-Chapter-1/" title="xv6 第一章"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 第一章</div></div></a></div><div><a href="/2022/08/31/xv6-Chapter-2/" title="xv6 第二章"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 第二章</div></div></a></div><div><a href="/2022/08/31/xv6-Chapter-3/" title="xv6 第三章"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 第三章</div></div></a></div><div><a href="/2022/08/31/xv6-Chapter-4/" title="xv6 第四章"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 第四章</div></div></a></div><div><a href="/2022/08/31/xv6-Chapter-5/" title="xv6 第五章"><img class="cover" src="/img/coding.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-08-31</div><div class="title">xv6 第五章</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/profile.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">kiloGrand</div><div class="author-info__description">coder && data-science researcher</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">46</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">6</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">5</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/kiloGrand/"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Lab-traps-Trap"><span class="toc-number">1.</span> <span class="toc-text">Lab traps: Trap</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Eliminate-allocation-from-sbrk-easy"><span class="toc-number">1.1.</span> <span class="toc-text">Eliminate allocation from sbrk() (easy)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Lazy-allocation-moderate"><span class="toc-number">1.2.</span> <span class="toc-text">Lazy allocation (moderate)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Lazytests-and-Usertests-moderate"><span class="toc-number">1.3.</span> <span class="toc-text">Lazytests and Usertests (moderate)</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BF%AE%E6%94%B9%E8%AE%B0%E5%BD%95"><span class="toc-number">1.4.</span> <span class="toc-text">修改记录</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/24/kuiper_infer-L14/" title="自制深度学习框架--实现Yolov5的推理">自制深度学习框架--实现Yolov5的推理</a><time datetime="2023-03-24T12:00:00.000Z" title="发表于 2023-03-24 20:00:00">2023-03-24</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/23/kuiper_infer-L13/" title="自制深度学习框架--实现ResNet网络的推理">自制深度学习框架--实现ResNet网络的推理</a><time datetime="2023-03-23T12:00:00.000Z" title="发表于 2023-03-23 20:00:00">2023-03-23</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/22/kuiper_infer-L12/" title="自制深度学习框架--算子的执行流程">自制深度学习框架--算子的执行流程</a><time datetime="2023-03-22T12:00:00.000Z" title="发表于 2023-03-22 20:00:00">2023-03-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/21/kuiper_infer-L11/" title="自制深度学习框架--再探Tensor类并构建计算图的图关系">自制深度学习框架--再探Tensor类并构建计算图的图关系</a><time datetime="2023-03-21T12:00:00.000Z" title="发表于 2023-03-21 20:00:00">2023-03-21</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/03/20/kuiper_infer-L10/" title="自制深度学习框架--Im2Col原理与卷积层的实现">自制深度学习框架--Im2Col原理与卷积层的实现</a><time datetime="2023-03-20T12:00:00.000Z" title="发表于 2023-03-20 20:00:00">2023-03-20</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2022 - 2023 By kiloGrand</div><div class="footer_custom_text">Hi, welcome to my blog!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.2
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container:not\([display]\)').forEach(node => {
            const target = node.parentNode
            if (target.nodeName.toLowerCase() === 'li') {
              target.parentNode.classList.add('has-jax')
            } else {
              target.classList.add('has-jax')
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>